/*
 * @Description: 事件总线机制 eventBus hook 钩子
 * @Author: James324
 * @Date: 2024-01-15 15:33:56
 * @LastEditors: James324
 * @LastEditTime: 2024-03-22 10:14:21
 */
import { Modal } from '@/instance';
import { isEqual } from 'lodash-es';
import { deepClone, deepUnRef } from '@/utils';
import mitt from 'mitt';
import type { AddData } from '@/store/type';

const emitter = mitt();

export type SetData = () => void;

export type Update = (setData: SetData) => void;

export default function useEmitter(storeKey?: keyof AddData, okCb?: () => void) {
    const emitOn = () => {
        emitOff(); // 绑定重复的之前先解绑上一次的
        emitter.on('tag-close--bus', (key: any) => {
            if (!isStart || isChange(key)) return ok();

            confirmClose();
        });
    };

    /**
     * @: 确定关闭弹框
     */
    const confirmClose = () => {
        Modal.destroyAll();
        Modal.confirm({
            title: '数据未保存，确定关闭吗？',
            content: '取消后将会放弃本次填写的内容',
            afterClose: () => {
                emitter.emit('modal-close--bus');
            },
            onOk: ok
        });
    };

    /**
     * @: 确定关闭
     */
    const ok = () => {
        emitter.emit('modal-confirm--bus');
        okCb && okCb();
    };

    const emitOff = () => {
        emitter.off('tag-close--bus');
    };

    onBeforeMount(() => {
        emitOn();
    });

    /**
     * @: 把ref数据归为普通数据
     */
    const unRef = (val: any): any => {
        for (const key in val) {
            val[key] = deepUnRef(val[key]);
        }
        return val;
    };

    /**
     * @: 开始对比
     */
    let isStart = false; // 是否开始
    const originalObj: anyObj = {}; // 原始对象
    const diffObj: anyObj = {}; // 需要对比的对象
    const startRecording = (key: string, payload: anyObj) => {
        diffObj[key] = payload;
        originalObj[key] = deepClone(payload);
        isStart = true;
    };

    /**
     * @: 判断是否更改
     */
    const isChange = (key: string) => {
        const currentData = unRef(diffObj[key]);

        deepClearUndef(currentData); // 清除为undefined的字段

        return isEqual(currentData, originalObj[key]);
    };

    const deepClearUndef = (obj: any) => {
        for (const key in obj) {
            if (obj[key] === undefined) {
                Reflect.deleteProperty(obj, key);
            } else if (typeof obj[key] === 'object') {
                deepClearUndef(obj[key]);
            }
        }
    };

    const store = addDataStore();

    const isUpdate: Update = setData => {
        if (storeKey && store[storeKey]?.update) {
            setData();
            store.handleAddData(storeKey, { ...store[storeKey], update: false });
        }
    };

    // 刷新时初始值设为true
    onBeforeMount(() => {
        if (storeKey) {
            store.handleAddData(storeKey, { ...store[storeKey], update: true });
        }
    });
    return {
        startRecording,
        emitter,
        isUpdate
    };
}
